package com.netty.demo.echo.server;

import java.net.InetSocketAddress;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class EchoServer {
	
	private final static int port = 8007;
	
	public void start() throws InterruptedException{
		ServerBootstrap bootstrap = new ServerBootstrap(); //引导辅助程序
		EventLoopGroup group = new NioEventLoopGroup(); //通过nio的方式接受连接和处理连接
		try {
			bootstrap.group(group)
				.channel(NioServerSocketChannel.class) //设置nio类型的channel
				.localAddress(new InetSocketAddress(port))//设置监听端口
				.childHandler(new ChannelInitializer<SocketChannel>() { //有连接到达时会创建一个channel
					// pipline 管理channel中的handler,在channel队列中添加一个handler来处理业务
					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						ch.pipeline().addLast("myHandler", new EchoServerHandler());
					}
				});
			ChannelFuture future = bootstrap.bind().sync(); //配置完成，绑定server，并通过sync同步方法阻塞直到绑定成功
			System.out.println(EchoServer.class.getName() + " started and listen on " + future.channel().localAddress());
			future.channel().closeFuture().sync(); //应用程序会一直等待，直到channel关闭
		} catch (Exception e) {
			e.getMessage();
		}finally {
			group.shutdownGracefully().sync();
		}
	}
	
	
	 public static void main(String[] args) {  
	        try {  
	            new EchoServer().start();  
	        } catch (InterruptedException e) {  
	            e.printStackTrace();  
	        }  
	    }  

	
//	public static void main(String[] args) {
//		EventLoopGroup boosGroup = new NioEventLoopGroup(1);
//		EventLoopGroup workGroup = new NioEventLoopGroup();
//		try {
//			ServerBootstrap bootstrap = new ServerBootstrap();
//			bootstrap.group(boosGroup, workGroup)
//				.channel(NioServerSocketChannel.class)
//				.option(ChannelOption.SO_BACKLOG, 100)
//				.handler(new LoggingHandler(LogLevel.INFO))
//				.childHandler(new ChannelInitializer<SocketChannel>() {
//					public void initChannel(SocketChannel ch){
//						ChannelPipeline pipeline = ch.pipeline();
//						pipeline.addLast(new EchoServerHandler());
//					}
//				});
//			ChannelFuture future = bootstrap.bind(8007).sync();
//			future.channel().closeFuture().sync();
//		} catch (Exception e) {
//			
//		}
//	}
}
